<?php 

require_once __DIR__.'/Err.php';

/**
* 用户类
*/


class User
{
	
	/**
	* 数据库连接对象
	* @param  PDO $_db
	**/

	private $_db;


	function __construct(PDO $_db)
	{
		$this->_db = $_db;
	}


	/**
	* 用户注册功能
	**/

	public function register($name,$passwd){
		if (empty($name)) {
			throw new Exception("用户名不能为空", Err::USERNAME_NOT_NULL);
			
		}
		if (empty($passwd)) {
			throw new Exception("用户密码不能为空", Err::USERPASSWD_NOT_NULL);
			
		}

		if ($this->_UserNameExis($name)) {
			throw new Exception("此用户名已存在", Err::USERNAME_IS_EXIS);
			
		}


		$create_time = date('Y-m-d H:i:s',time());
		$sql = "insert into user(name,passwd,create_time) values (:name,:passwd,:create_time)";
	
		$passwd = $this->_md5($passwd);
		$sm = $this->_db->prepare($sql);
		// $sm->bindParam(':id',$id);
		$sm->bindParam(':name',$name);
		$sm->bindParam(':passwd',$passwd);
		$sm->bindParam(':create_time',$create_time);
		// print_r($sm);exit();
		if (!$sm->execute()) {
			throw new Exception("注册失败", Err::USER_REGISTER_FAIL);
			
		}

		return [
			'username'=>$name,
			'user_id'=>$this->_db->lastInsertId(),
			'add_time'=>$create_time
		];
		

	}


	/**
	* 判断用户名是否存在
	* @param var $name  用户名
	* return bool 
	**/

	private function _UserNameExis($name) {
		$sql = "select * from user where name = :name";
		$sm = $this->_db->prepare($sql);
		$sm->bindParam('name',$name);
		$sm->execute();
		$re = $sm->fetch(PDO::FETCH_ASSOC);
		return !empty($re);
	}


	/**
	* md5加盐注册
	*@param $passwd  用户密码
	*return mixd 
	**/
	private function _md5($passwd){
		return md5($passwd.SALT);
	}


	public function login($name,$passwd){
		if (empty($name)) {
			throw new Exception("用户名不能为空", Err::USERNAME_NOT_NULL);
			
		}
		if (empty($passwd)) {
			throw new Exception("用户密码不能为空", Err::USERPASSWD_NOT_NULL);
			
		}

		$sql = "select name,passwd from user where (name= :name and passwd = :passwd)";
		$passwd = $this->_md5($passwd);
		$sm = $this->_db->prepare($sql);
		$sm->bindParam(':name',$name);
		$sm->bindParam(':passwd',$passwd);
		if (!$sm->execute()) {
			throw new Exception("登陆失败", Err::USER_LOGIN_FAIL);
			
		}
		
		$re = $sm->fetch(PDO::FETCH_ASSOC);
		if (empty($re)) {
			throw new Exception("用户名或者密码错误", Err::USER_NAMEORPASSWD_FAIL);
			
		}
		return $re;

	}

	public function do() {
		print_r($this->_db);
	}
}
